package circle;

/**
 * @author 陈艺博
 * @date 2021-02-25 10:43
 * @description 循环队列
 **/
public class CircleQueue<E> {

    private int front;
    private int size;
    private E[] elements;
    private static final int DEFAULT_CAPACITY = 10;

    public CircleQueue() {
        elements = (E[]) new Object[DEFAULT_CAPACITY];
    }

    public int size() {
        return size;
    }

    public boolean isEmpty() {
        return size == 0;
    }

    /**
     * 入队,元素添加到队尾（rear）
     *
     * @param element 元素
     */
    public void enqueue(E element) {
        // 动态扩容
        ensureCapacity(size + 1);
        elements[index(size)] = element;
        size++;
    }

    /**
     * 出队
     *
     * @return 队头（front）元素
     */
    public E deQueue() {
        E frontElem = elements[front];
        elements[front] = null;
        front = index(1);
        size--;
        return frontElem;
    }

    /**
     * 获取队头元素
     *
     * @return 对头元素
     */
    public E front() {
        return elements[front];
    }

    private void ensureCapacity(int capacity) {
        int oldCapacity = elements.length;
        if (oldCapacity >= capacity) {
            return;
        }
        //新容量的1.5倍
        int newCapacity = oldCapacity + (oldCapacity >> 1);
        E[] newElements = (E[]) new Object[newCapacity];
        for (int i = 0; i < size; i++) {
            newElements[i] = elements[index(i)];
        }
        elements = newElements;
        front = 0;
    }

    /**
     * 将逻辑索引index, 装换为队列的真实索引
     *
     * @param index 逻辑索引
     * @return 队列对应的真实索引
     */
    private int index(int index) {
        return (index + front) % elements.length;
    }

    @Override
    public String toString() {
        StringBuilder string = new StringBuilder();
        string.append("Capacity = ").append(elements.length)
                .append(", Size = ").append(size)
                .append(", Front = ").append(front)
                .append(", Element = [");
        for (int i = 0; i < elements.length; i++) {
            if (i != 0) {
                string.append(", ");
            }
            string.append(elements[i]);
        }
        string.append(" ]");
        return string.toString();
    }
}
